<template>
  <div>
    <el-row>
      <h5 class="greenFontColor">通用普查附表结构设计 </h5>
    </el-row>
    <el-row>
      <el-button size="small" @click="add">添加一行</el-button>
    </el-row>
    <el-table :data="list" style="width: 100%" height="400" highlight-current-row>
      <el-table-column prop="code" label="代码" width="180">
        <template slot-scope="scope">
          <el-input v-model="scope.row.code" v-if="scope.row.id == editId" size="small"></el-input>
          <span v-else>{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="指标名称" width="180">
        <template slot-scope="scope">
          <el-input v-model="scope.row.name" v-if="scope.row.id == editId" size="small"></el-input>
          <span v-else>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="investData" label="普查数据">
        <template slot-scope="scope">
          <el-input v-model="scope.row.investData" v-if="scope.row.id == editId" size="small"></el-input>
          <span v-else>{{ scope.row.investData }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateData" label="更新数据">
        <template slot-scope="scope">
          <el-input v-model="scope.row.updateData" v-if="scope.row.id == editId" size="small"></el-input>
          <span v-else>{{ scope.row.updateData }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="计量单位">
        <template slot-scope="scope">
          <el-select value="" ref="unitSelect" v-if="scope.row.id == editId" v-model="scope.row.unit" filterable
            allow-create clearable placeholder="">
            <el-option v-for="item in unitOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <span v-else>{{ scope.row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="text" v-if="scope.row.id != editId" @click="changeClick(scope.row)" size="small">编辑</el-button>
          <el-button type="text" v-if="scope.row.id != editId" @click="delClick(scope.row)" size="small">删除</el-button>
          <el-button type="text" v-if="scope.row.id == editId" @click="cancelClick(scope.row)" size="small">取消</el-button>
          <el-button type="text" v-if="scope.row.id == editId" @click="saveClick(scope.row)" size="small">保存</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script lang="ts">
import { Component,Emit, Prop, Vue,Watch } from 'vue-property-decorator';
import {addSubStructureCommon,queryByStructureId,updateSubStructureCommon} from '@/api/investSubStructureCommon';
@Component
export default class SubTable extends Vue {
 
  @Prop() private subStructureId: any;//查询参数
  @Prop({
    default: () => ({//表格样式参数
      stripe: false, // 是否为斑马纹 table
      loading: false, // 是否添加表格loading加载动画
      highlightCurrentRow: false, // 是否支持当前行高亮显示
      multipleSelect: false, // 是否支持列表项选中功能
      defaultSort: {
        prop: 'id',
        order: 'descending'
      },
      border: false,
      expand: false,
      expandColumn: 3,
      expandSize: '',
      align: 'center',//对齐方式
      index: false,//是否显示序号
    })
  }) private options!: any;

  public list: Array<any> = [];

  hQuery: any = {};//查询参数
  editId = '';
  editData = {};

  private unitOptions = [{
    value: '乙',
    label: '乙'
  }, {
    value: '——',
    label: '——'
  }, {
    value: '（文字说明）',
    label: '（文字说明）'
  }, {
    value: '（单选）',
    label: '（单选）'
  }, {
    value: '平方米',
    label: '平方米'
  },
  {
    value: '人',
    label: '人'
  },
  {
    value: '个',
    label: '个'
  },
  {
    value: '万元',
    label: '万元'
  },
  {
    value: '（多选）',
    label: '（多选）'
  }];

  delClick(row) {
    //删除接口 成功以后 this.editId = ''
  }
  

  refreshData() {
    if(this.subStructureId){
      queryByStructureId({'id':this.subStructureId}).then((res: any) => {
        if(res.data){
          this.list = JSON.parse(JSON.stringify(res.data));
        }
        this.handleEvent(res.data);
        //判断是否选中
      }).catch((e) => {
        console.error(e);
      });
    }else{
      if(this.list.length > 0){
        this.handleEvent(this.list);
      }
    }

  }

  @Emit('handleEvent')
  @Emit('handle-event')
  handleEvent(val) {
    return val;
  }

  cancelClick(row) {
    if (row.id) {
      for (let i in row) {
        row[i] = this.editData[i]
      }
      this.editId = ''
    } else {
      this.list.forEach((item, index) => {
        if (item.id == '') {
          this.list.splice(index, 1)
        }
      })
    }
  }

  saveClick(row) {
    //保存接口 成功以后 this.editId = ''
    if(this.subStructureId){
      row.subSturctureId = this.subStructureId;
      if(row.id){
        updateSubStructureCommon(row).then((res: any) => {
          this.refreshData();
          this.editId = '';
        //判断是否选中
        }).catch((e) => {
          console.error(e);
        });
      }else{
        addSubStructureCommon(row).then((res: any) => {
          this.refreshData();
          this.editId = '';
        //判断是否选中
        }).catch((e) => {
          console.error(e);
        });
      }
    }else{
      row.id = "newAdd"+ Math.random() *2000000;
      this.editId = '';
      this.refreshData();
    }
  }

  changeClick(row) {
      if (this.list.some((item) => {
        return item.id == ''
      })) {
        this.$message({ message: '请先保存', type: 'warning' });
        return
      }
    this.editData = JSON.parse(JSON.stringify(row))    //把当前行数据存一份，取消的时候行数据还原
    this.editId = row.id
  }
  handleClick(row) {
    console.log(row);
  }
  add() {
    if (this.editId != '') {
      this.$message({ message: '请先保存', type: 'warning' }); return;
    }
    if (this.list.some((item) => { return item.id == '' })) {
      this.$message({ message: '请先保存', type: 'warning' });
      return;
    }
    this.list.push(
      {
        'code': '——', 'name': '——',
        'investData': '——', 'updateData': '——', 'unit': '——', 'contentType': '0', 'id': '',
        'subStructureId':this.subStructureId || '','status':'0'
      }
    )
  }
  @Watch('subStructureId')
  onchangeValue(newVal: string, oldVal: string){
    this.refreshData();
  }
}
</script>